<?php
namespace Common\uploadStorage;
use Qiniu\Auth;
use Qiniu\Storage\BucketManager;
use Qiniu\Storage\UploadManager;

class Qiniu{
    protected $error;
    /**
     * 执行上传
     * @return bool|mixed
     * @throws \Exception
     */
    public function upload($up_file,$up_config = [])
    {
        // 构建鉴权对象
        $auth = new Auth($up_config['access_key'], $up_config['secret_key']);

		// 要上传的空间
        $token = $auth->uploadToken($up_config['bucket']);
        // 初始化 UploadManager 对象并进行文件的上传
        $uploadMgr = new UploadManager();
        // 调用 UploadManager 的 putFile 方法进行文件的上传
        list(, $error) = $uploadMgr->putFile($token, $up_config['file_name'], $up_file['tmp_name']);
        /* @var $error \Qiniu\Http\Error */
        if ($error !== null) {
            $this->error = $error->message();
            return false;
        }
        return true;
    }

    /**
     * 删除文件
     * @param $fileName
     * @return bool|mixed
     */
    public function deleteFile($fileName)
    {
        // 构建鉴权对象
        $auth = new Auth($this->config['access_key'], $this->config['secret_key']);
        // 初始化 UploadManager 对象并进行文件的上传
        $bucketMgr = new BucketManager($auth);
        /* @var $error \Qiniu\Http\Error */
        $error = $bucketMgr->delete($this->config['bucket'], $fileName);
        if ($error !== null) {
            $this->error = $error->message();
            return false;
        }
        return true;
    }

    /**
     * 获取错误信息
     * @return mixed
     */
    public function getError()
    {
        return $this->error;
    }
}
